﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mattress.Engine.Matlab {
    internal class mxStructArray : mxArray {
        public mxStructArray(SafeArrayPtr pa) : base(pa, mxArrayType.Struct) { }

        public int FieldCount {
            get { return matrix.mxGetNumberOfFields(this.NativeObject); }
        }

        public mxArray GetField(int index, int fieldNum) {
            if (index < 0 || index >= this.Length)
                throw new ArgumentOutOfRangeException("The index must be range from 0 to the length of the array.");

            int fieldCount = this.FieldCount;
            if (fieldNum < 0 || fieldNum >= fieldCount)
                throw new ArgumentOutOfRangeException("The fieldnum must be range from 0 to the number of the field.");

            return mxArray.Create(matrix.mxGetFieldByNumber(this.NativeObject, index, fieldNum));
        }

        public mxArray GetField(int index, string fieldName) {
            if (index < 0 || index >= this.Length)
                throw new ArgumentOutOfRangeException("The index must be range from 0 to the length of the array.");

            SafeArrayPtr ptr = matrix.mxGetField(this.NativeObject, index, fieldName);
            if (ptr.IsInvalid)
                throw new ArgumentException("The fieldName is not exists in struct.");

            return mxArray.Create(ptr);
        }

        public string[] GetFieldNames() {
            int fieldCount = this.FieldCount;
            string[] fieldNames = new string[fieldCount];

            for (int i = 0; i < fieldCount; i++) {
                fieldNames[i] = matrix.mxGetFieldNameByNumber(this.NativeObject, i);
            }

            return fieldNames;
        }
    }
}
